/**
 * 设置页面逻辑
 */

const { ipcRenderer } = require('electron');
const log = require('electron-log');
const {
  showNotification,
  setupWindowControls,
  navigateToPage,
  getUserData
} = require('../utils/common');

// 默认设置
const defaultSettings = {
  autoStart: false,
  minimizeToTray: true,
  confirmDelete: true,
  maxConcurrent: 3,
  chunkSize: 5,
  autoRetry: true,
  skipExisting: false,
  ftpHost: process.env.FTP_HOST || 'drive.kbin.cc',
  ftpPort: parseInt(process.env.FTP_PORT) || 21,
  ftpTimeout: 30,
  ftpPassive: true,
  theme: 'light',
  fontSize: 'medium'
};

// 页面初始化
window.addEventListener('DOMContentLoaded', () => {
  // 检查登录状态
  const userData = getUserData();
  if (!userData) {
    navigateToPage('login');
    return;
  }

  // 设置窗口控制
  setupWindowControls();

  // 绑定事件
  bindEvents();

  // 加载设置
  loadSettings();

  log.info('设置页面初始化完成');
});

// 绑定事件
function bindEvents() {
  // 导航切换
  const navItems = document.querySelectorAll('.nav-item');
  navItems.forEach(item => {
    item.addEventListener('click', () => {
      const tabName = item.dataset.tab;
      switchTab(tabName);
    });
  });

  // 按钮事件
  document.getElementById('back-btn')?.addEventListener('click', () => {
    navigateToPage('main');
  });

  document.getElementById('save-btn')?.addEventListener('click', saveSettings);
  document.getElementById('reset-btn')?.addEventListener('click', resetSettings);
}

// 切换标签页
function switchTab(tabName) {
  // 更新导航高亮
  document.querySelectorAll('.nav-item').forEach(item => {
    item.classList.remove('active');
  });
  document.querySelector(`[data-tab="${tabName}"]`)?.classList.add('active');

  // 切换内容
  document.querySelectorAll('.settings-tab').forEach(tab => {
    tab.classList.remove('active');
  });
  document.getElementById(`tab-${tabName}`)?.classList.add('active');
}

// 加载设置
function loadSettings() {
  const settings = getSettings();

  // 常规设置
  document.getElementById('auto-start').checked = settings.autoStart;
  document.getElementById('minimize-to-tray').checked = settings.minimizeToTray;
  document.getElementById('confirm-delete').checked = settings.confirmDelete;

  // 传输设置
  document.getElementById('max-concurrent').value = settings.maxConcurrent;
  document.getElementById('chunk-size').value = settings.chunkSize;
  document.getElementById('auto-retry').checked = settings.autoRetry;
  document.getElementById('skip-existing').checked = settings.skipExisting;

  // FTP设置
  document.getElementById('ftp-host').value = settings.ftpHost;
  document.getElementById('ftp-port').value = settings.ftpPort;
  document.getElementById('ftp-timeout').value = settings.ftpTimeout;
  document.getElementById('ftp-passive').checked = settings.ftpPassive;

  // 外观设置
  document.getElementById('theme').value = settings.theme;
  document.getElementById('font-size').value = settings.fontSize;

  log.info('设置已加载');
}

// 保存设置
function saveSettings() {
  const settings = {
    // 常规设置
    autoStart: document.getElementById('auto-start').checked,
    minimizeToTray: document.getElementById('minimize-to-tray').checked,
    confirmDelete: document.getElementById('confirm-delete').checked,

    // 传输设置
    maxConcurrent: parseInt(document.getElementById('max-concurrent').value),
    chunkSize: parseInt(document.getElementById('chunk-size').value),
    autoRetry: document.getElementById('auto-retry').checked,
    skipExisting: document.getElementById('skip-existing').checked,

    // FTP设置
    ftpHost: document.getElementById('ftp-host').value,
    ftpPort: parseInt(document.getElementById('ftp-port').value),
    ftpTimeout: parseInt(document.getElementById('ftp-timeout').value),
    ftpPassive: document.getElementById('ftp-passive').checked,

    // 外观设置
    theme: document.getElementById('theme').value,
    fontSize: document.getElementById('font-size').value
  };

  // 验证设置
  if (settings.maxConcurrent < 1 || settings.maxConcurrent > 10) {
    showNotification('最大并发数必须在1-10之间', 'warning');
    return;
  }

  if (settings.chunkSize < 1 || settings.chunkSize > 100) {
    showNotification('分片大小必须在1-100MB之间', 'warning');
    return;
  }

  // 保存到本地存储
  localStorage.setItem('appSettings', JSON.stringify(settings));

  // 应用一些设置
  applySettings(settings);

  showNotification('设置已保存', 'success');
  log.info('设置已保存:', settings);
}

// 重置设置
function resetSettings() {
  if (confirm('确定要恢复默认设置吗？')) {
    localStorage.setItem('appSettings', JSON.stringify(defaultSettings));
    loadSettings();
    showNotification('已恢复默认设置', 'info');
    log.info('设置已重置为默认值');
  }
}

// 获取设置
function getSettings() {
  const saved = localStorage.getItem('appSettings');
  if (saved) {
    try {
      return { ...defaultSettings, ...JSON.parse(saved) };
    } catch (error) {
      log.error('读取设置失败:', error);
      return defaultSettings;
    }
  }
  return defaultSettings;
}

// 应用设置
function applySettings(settings) {
  // 应用主题
  if (settings.theme === 'dark') {
    document.body.classList.add('dark-theme');
  } else {
    document.body.classList.remove('dark-theme');
  }

  // 应用字体大小
  document.body.classList.remove('font-small', 'font-medium', 'font-large');
  document.body.classList.add(`font-${settings.fontSize}`);

  // 通知主进程应用一些系统级设置
  ipcRenderer.send('apply-settings', settings);
}

// 导出设置获取函数供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
  module.exports = { getSettings };
}
